package com.ipad.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.cooltechworks.views.shimmer.ShimmerRecyclerView;
import com.google.zxing.WriterException;
import com.ipad.R;
import com.ipad.bean.Delivery;
import com.ipad.bean.Product;
import com.ipad.bean.Warehouse;
import com.ipad.net.entity.DeliveryContainerEntity;
import com.ipad.net.entity.DeliveryCount;
import com.ipad.net.entity.DeliveryListEntity;
import com.ipad.net.entity.DeliveryListInfoEntity;
import com.ipad.net.presenter.StroePresenter;
import com.ipad.net.view.IStoreView;
import com.ipad.ui.BaseActivity;
import com.ipad.ui.adapter.DeliveryInfoAdapter;
import com.ipad.ui.adapter.DeliveryListAdapter;
import com.ipad.ui.fragmen.ImgDialogFragment;
import com.ipad.ui.fragmen.WarehousV2Fragment;
import com.ipad.utils.MCodeUtils;
import com.ipad.utils.SharePerenceUtils;
import com.ipad.utils.ToasUtils;
import com.ipad.view.dialog.SignDialog;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.encoding.EncodingHandler;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class DeliveryActivity extends BaseActivity implements IStoreView,WarehousV2Fragment.OnSelectWarehouse,EasyPermissions.PermissionCallbacks {
    @BindView(R.id.delivery_refresh)
    RefreshLayout delivery_refresh;
    @BindView(R.id.delivery_info_refresh)
    RefreshLayout delivery_info_refresh;
    @BindView(R.id.delivery_back)
    ImageView delivery_back;
    @BindView(R.id.delivery_toolbar)
    Toolbar delivery_toolbar;
    @BindView(R.id.delivery_search)
    EditText delivery_search;
    @BindView(R.id.delivery_list)
    ListView delivery_list;
    @BindView(R.id.delivery_img_code)
    ImageView delivery_img_code;
    @BindView(R.id.delivery_bill_code)
    TextView delivery_bill_code;
    @BindView(R.id.delivery_req_store)
    TextView delivery_req_store;
    @BindView(R.id.delivery_total_num)
    TextView delivery_total_num;
    @BindView(R.id.delivery_creater)
    TextView delivery_creater;
    @BindView(R.id.delivery_select_warehouse)
    TextView delivery_select_warehouse;
    @BindView(R.id.delivery_list_info)
    RecyclerView delivery_list_info;
    @BindView(R.id.delivery_confirm_sign)
    Button delivery_confirm_sign;

    List<Delivery> deliveries = new ArrayList<>();
    DeliveryListAdapter deliveryListAdapter;

    List<Product> details = new ArrayList<>();
    DeliveryInfoAdapter deliveryInfoAdapter;

    StroePresenter stroePresenter;

    int details_page = 1;
    int details_total_page = 1;

    int page = 1;
    int rows = 10;
    String out_warehouse_id = "";
    String req_warehouse_id = "";
    String bill_code = "";
    String sign_name = "";
    private String TAG = "delivery";
    private int mPosition = 0;
    private String sign_id;


    @Override
    public int getLayoutId() {
        return R.layout.activity_delivery;
    }

    public void demo(){
        delivery_req_store.setText("神经外科门诊");
        delivery_creater.setText("张勇");
        delivery_total_num.setText("48");
        delivery_bill_code.setText("SD1908140001");
        for (int i = 0 ;i<10;i++){
            Delivery delivery = new Delivery();
            delivery.setBillCode("SD190814000"+i);
            delivery.setReqWarehouseName("设备科室");
            deliveries.add(delivery);
        }

        Product product = new Product();
        Product.ProductVoBean productVoBean = new Product.ProductVoBean();
        productVoBean.setErpCode("588168");
        productVoBean.setName("一次性使用无菌口罩");
        productVoBean.setSpec("18*19");
        productVoBean.setModel("");
        productVoBean.setUnits("个");
        productVoBean.setPurchasePrice(new BigDecimal(11));
        productVoBean.setSupplierNames("河南省宇安医疗科技开发有限公司");
        product.setProductVo(productVoBean);
        product.setBatchNum("D323");
        product.setValidDate("2022-07-013");
        product.setOutQuantity(new BigDecimal(6));

        details.add(product);


        Product product2 = new Product();
        Product.ProductVoBean productVoBean2 = new Product.ProductVoBean();
        productVoBean2.setErpCode("871785");
        productVoBean2.setName("金属锁定接骨板");
        productVoBean2.setSpec("5+4H280");
        productVoBean2.setModel("6ml");
        productVoBean2.setUnits("个");
        productVoBean2.setPurchasePrice(new BigDecimal(112));
        productVoBean2.setSupplierNames("朝阳市则方商贸有限公司");
        product2.setProductVo(productVoBean2);
        product2.setBatchNum("S234DG3");
        product2.setValidDate("2022-02-03");
        product2.setOutQuantity(new BigDecimal(3));

        details.add(product2);



        Product product3 = new Product();
        Product.ProductVoBean productVoBean3 = new Product.ProductVoBean();
        productVoBean3.setErpCode("864715");
        productVoBean3.setName("CT专用高压注射针筒");
        productVoBean3.setSpec("6ml");
        productVoBean3.setModel("6ml");
        productVoBean3.setUnits("支");
        productVoBean3.setPurchasePrice(new BigDecimal(13));
        productVoBean3.setSupplierNames("沧州永康医药用品有限公司");
        product3.setProductVo(productVoBean3);
        product3.setBatchNum("8334KS");
        product3.setValidDate("2019-01-04");
        product3.setOutQuantity(new BigDecimal(12));

        details.add(product3);




        Product product4 = new Product();
        Product.ProductVoBean productVoBean4 = new Product.ProductVoBean();
        productVoBean4.setErpCode("546874");
        productVoBean4.setName("造血导管");
        productVoBean4.setSpec("6mm");
        productVoBean4.setModel("6mm");
        productVoBean4.setUnits("个");
        productVoBean4.setSupplierNames("长春康元建医学科技有限公司");
        productVoBean4.setPurchasePrice(new BigDecimal(136));
        product4.setProductVo(productVoBean4);
        product4.setBatchNum("UE9342");
        product4.setValidDate("2025-07-11");
        product4.setOutQuantity(new BigDecimal(8));

        details.add(product4);




        Product product5 = new Product();
        Product.ProductVoBean productVoBean5 = new Product.ProductVoBean();
        productVoBean5.setErpCode("94828");
        productVoBean5.setName("药物洗脱冠脉支架系统");
        productVoBean5.setSpec(" RN-42(10 14 16)40");
        productVoBean5.setModel("");
        productVoBean5.setUnits("根");
        productVoBean5.setSupplierNames("沈阳沃隆恒晟商贸有限公司");
        productVoBean5.setPurchasePrice(new BigDecimal(200));
        product5.setProductVo(productVoBean5);
        product5.setBatchNum("13");
        product5.setValidDate("2020-07-29");
        product5.setOutQuantity(new BigDecimal(3));

        details.add(product5);




        Product product6 = new Product();
        Product.ProductVoBean productVoBean7 = new Product.ProductVoBean();
        productVoBean7.setErpCode("94122");
        productVoBean7.setName("一次性使用连接管");
        productVoBean7.setSpec("LJG-J(20/盒)");
        productVoBean7.setModel("6ml");
        productVoBean7.setUnits("支");
        productVoBean7.setSupplierNames("北京泉辉和奕医疗器械有限公司");
        productVoBean7.setPurchasePrice(new BigDecimal(11.5));
        product6.setProductVo(productVoBean7);
        product6.setBatchNum("skb55");
        product6.setValidDate("2019-05-05");
        product6.setOutQuantity(new BigDecimal(5));

        details.add(product6);




        Product product8 = new Product();
        Product.ProductVoBean productVoBean8 = new Product.ProductVoBean();
        productVoBean8.setErpCode("95460");
        productVoBean8.setName("密闭式静脉留置针");
        productVoBean8.setSpec("1.1mm*30mm直型");
        productVoBean8.setModel("");
        productVoBean8.setUnits("支");
        productVoBean8.setSupplierNames("沈阳百利科曼商贸有限公司");
        productVoBean8.setPurchasePrice(new BigDecimal(18.5));
        product8.setProductVo(productVoBean8);
        product8.setBatchNum("SW112");
        product8.setValidDate("2020-06-03");
        product8.setOutQuantity(new BigDecimal(5));

        details.add(product8);




        Product product9 = new Product();
        Product.ProductVoBean productVoBean9 = new Product.ProductVoBean();
        productVoBean9.setErpCode("588168");
        productVoBean9.setName("医用面罩");
        productVoBean9.setSpec("5#可充气式");
        productVoBean9.setModel("");
        productVoBean9.setUnits("张");
        productVoBean9.setSupplierNames("沈阳百世华丽商贸有限公司");
        productVoBean9.setPurchasePrice(new BigDecimal(24.5));
        product9.setProductVo(productVoBean9);
        product9.setBatchNum("Y6683");
        product9.setValidDate("2020-04-07");
        product9.setOutQuantity(new BigDecimal(6));

        details.add(product9);

        Log.e(TAG, "initView: "+details.size() );


    }
    @Override
    public void initView() {

        demo();

        delivery_list_info.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        deliveryInfoAdapter = new DeliveryInfoAdapter(details, this);
        delivery_list_info.setAdapter(deliveryInfoAdapter);


        delivery_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (deliveryListAdapter.getChecked_position() == position) {
                    return;
                }
                delivery_creater.setText(deliveries.get(position).getCreateName());
                //
                try {
                    BigDecimal total = deliveries.get(position).getOutQuantity().add(deliveries.get(position).getInQuantity());
                    delivery_total_num.setText(total.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }


                deliveryListAdapter.setChecked_position(position);
                //选择配送单
                MCodeUtils.setOneCodeImage(deliveries.get(position).getBillCode(), delivery_img_code, DeliveryActivity.this);
                delivery_bill_code.setText(deliveries.get(position).getBillCode());
                delivery_req_store.setText(deliveries.get(position).getReqWarehouseName());

                details.clear();
                deliveryInfoAdapter.notifyDataSetChanged();
                details_page = 1;
                details_total_page = 1;
                mPosition = position;
                Log.e(TAG, "onItemClick: " + deliveries.get(position).getId());
                getDeliveryDetail(deliveries.get(position).getId() + "");
            }
        });
        delivery_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                bill_code = s.toString();
                deliveries.clear();
                deliveryListAdapter.notifyDataSetChanged();
                getDeliveryList(bill_code);
            }
        });

        delivery_select_warehouse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WarehousV2Fragment warehousV2Fragment = WarehousV2Fragment.newInstance(1);
                warehousV2Fragment.show(getSupportFragmentManager(), "");
            }
        });
        delivery_img_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (delivery_img_code.getDrawable() == null || delivery_bill_code.getText().toString() == null || delivery_bill_code.getText().toString().equals("")) {
                    return;
                }
                ImgDialogFragment imgDialogFragment = ImgDialogFragment.newInstance(delivery_bill_code.getText().toString());
                imgDialogFragment.show(getSupportFragmentManager(), "");
            }
        });

        delivery_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //刷新
        delivery_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                resetDetailsUI();
                mPosition = 0;

                deliveryListAdapter.setChecked_position(-1);
                deliveries.clear();
                deliveryListAdapter.notifyDataSetChanged();
                page = 1;
                getDeliveryList(bill_code);


            }
        });
        delivery_refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                page++;
                getDeliveryList(bill_code);
            }
        });
        delivery_info_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                details.clear();
                deliveryInfoAdapter.notifyDataSetChanged();
                details_page = 1;
                details_total_page = 1;

                getDeliveryDetail(deliveries.get(mPosition).getId() + "");

            }
        });

        delivery_info_refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                if (details_page < details_total_page) {
                    details_page++;
                    getDeliveryDetail(deliveries.get(mPosition).getId() + "");
                }
                delivery_info_refresh.finishLoadMore();
            }
        });

        delivery_confirm_sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] perms = {
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                };
                if (!EasyPermissions.hasPermissions(DeliveryActivity.this,perms)){
                    EasyPermissions.requestPermissions(DeliveryActivity.this,"",0x11,perms);
                    return;
                }



                try {
                    sign_name = delivery_bill_code.getText().toString();
                    sign_id = deliveries.get(mPosition).getId() + "";
                } catch (Exception e) {
                    e.printStackTrace();
                }



                SignDialog signDialog = SignDialog.newInstance(sign_name,sign_id,"","");
                signDialog.show(getSupportFragmentManager(),"sign_name");
            }
        });

    }

    @Override
    public void initData() {
        out_warehouse_id = SharePerenceUtils.getWarehouseId(this);

        stroePresenter = new StroePresenter();
        stroePresenter.attchView(this);

        deliveryListAdapter = new DeliveryListAdapter(deliveries, this);
        delivery_list.setAdapter(deliveryListAdapter);

        getDeliveryList(bill_code);
    }

    public void getDeliveryList(String bill_code) {
        if (stroePresenter != null) {
            stroePresenter.getDeliveryList(bill_code, "", "", "0", req_warehouse_id, "", "", "", out_warehouse_id, page + "", rows + "", SharePerenceUtils.getToken(this), false);
        }
    }

    public void getDeliveryDetail(String id) {
        if (stroePresenter != null) {
            stroePresenter.getDeliveryDetails(id, details_page + "", rows + "", SharePerenceUtils.getToken(this), false);
        }
    }

    @Override
    public void setToolbar() {
        setSupportActionBar(delivery_toolbar);
    }

    @Override
    public void stopLoading() {
        if (delivery_refresh.isLoading()) {
            delivery_refresh.finishLoadMore();
        }
        if (delivery_refresh.isRefreshing()) {
            delivery_refresh.finishRefresh();
        }
        if (delivery_info_refresh.isLoading()) {
            delivery_info_refresh.finishLoadMore();
        }
        if (delivery_info_refresh.isRefreshing()) {
            delivery_info_refresh.finishRefresh();
        }
    }

    @Override
    public void loading(String msg) {

    }

    @Override
    public void error(String msg) {
        ToasUtils.getToast(msg, this);
    }

    @Override
    public void getDeliveryListSuccess(DeliveryListEntity deliveryListEntity) {
        Log.e(TAG, "getDeliveryListSuccess: ");
        if (deliveryListEntity != null) {
            if (deliveryListEntity.getRecords() != null && deliveryListEntity.getRecords().size() != 0) {
                deliveries.addAll(deliveryListEntity.getRecords());
            }
        }
        deliveryListAdapter.notifyDataSetChanged();
    }

    @Override
    public void getDeliveryDetailSuccess(DeliveryListInfoEntity deliveryListInfoEntity) {
        if (deliveryListInfoEntity != null) {
            if (deliveryListInfoEntity.getRecords() != null && deliveryListInfoEntity.getRecords().size() != 0) {
                details.addAll(deliveryListInfoEntity.getRecords());
                details_total_page = deliveryListInfoEntity.getPages();
            }
        }
        deliveryInfoAdapter.notifyDataSetChanged();
    }

    @Override
    public void getDeliveryCountSuccess(DeliveryCount count) {

    }

    @Override
    public void getDeliveryByContainerSuccess(DeliveryContainerEntity count) {

    }

    public void resetDetailsUI(){
        delivery_bill_code.setText("");
        delivery_req_store.setText("");
        delivery_total_num.setText("");
        delivery_creater.setText("");
        req_warehouse_id = "";
        delivery_select_warehouse.setText(getResources().getString(R.string.delivery_select_warehouse));
        delivery_img_code.setImageResource(0);
        details.clear();
        deliveryInfoAdapter.notifyDataSetChanged();
        details_page = 1;
        details_total_page = 1;
    }

    @Override
    public void selectWarehouse(Warehouse warehouse) {
        deliveries.clear();
        deliveryListAdapter.notifyDataSetChanged();
        details.clear();
        deliveryInfoAdapter.notifyDataSetChanged();

        req_warehouse_id = warehouse.getId()+"";
        delivery_select_warehouse.setText(warehouse.getName());
        getDeliveryList(bill_code);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);

    }


    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }
}
